#include "FileUtil.h"
#include <stdio.h>
#include "zip.h"
#include "errno.h"
#include "stdlib.h"
#include "string.h"
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#include "glib.h"

//读取文件内容到缓冲区，并返回文件大小
int readFile(FileContent* result,char* filePath){
  //打开文件
  FILE *file = fopen(filePath,"rb");

  //获取文件大小
  fseek(file,0,SEEK_END);
  int length = ftell(file);
  result->length = length;
  fseek(file,0,SEEK_SET);

  //读取文件内容
  result->content = (char*)calloc(1,length);
  fread((void*)result->content, sizeof(char), length, file);

  fclose(file);
  //返回FIlecontent
  return 1;
}

int writeFile(char* path,const char* buffer, int length){
    //打开文件
    FILE *file = fopen(path,"wb");

    //写文件
    fwrite(buffer,1,length,file);

    //关闭
    fclose(file);
    return 1;
}

int pmkdir(const char *path) 
{ 
    char name[1024]; 
    strcpy(name, path); 
    int i, len = strlen(name); 

    if (name[len-1]!='/') {
        strcat(name, "/");
    } 

    len = strlen(name); 

    for (i=1 ; i<len ; i++) { 
        if (name[i]=='/') { 
            name[i] = 0; 
            if ( access(name, F_OK) !=0 ) { 
                if (mkdir(name, 0755) == -1) {  
                    //LOGE("mkdir error");  
                    return -1;  
                } 
            }
            name[i] = '/'; 
        } 
    } 

    return 0; 
} 

void unzip(char *zipPath){
    int err = 0;
    char strerr[1024];
    struct zip *z = NULL;

    z = zip_open(zipPath, ZIP_CREATE, &err);
    if (z != NULL) {

        zip_int64_t i, c = zip_get_num_entries(z, ZIP_FL_UNCHANGED);
        for (i=0; i<c ; i++) {
            const char * name = zip_get_name(z, i, ZIP_FL_ENC_GUESS);
            //LOGI("find %s\n", name);
            char *d = strdup(name);
            if (d != NULL) {
                char *p = strrchr(d, '/');
                if(p != NULL) {
                    *p = '\0';
                    pmkdir(d);
                }
                free(d);

                FILE *fp = fopen(name, "w+b");
                struct zip_file *f = zip_fopen(z, name, 0);
                if (f != NULL && fp != NULL) {
                    zip_int64_t j, n = 0;
                    char buf[8192] = "";
                    while ((n = zip_fread(f, buf, sizeof(buf))) > 0) {
                        for (j=0;j<n;j++) {
                            putc(buf[j], fp);
                        }
                    }
                    fclose(fp);
                    zip_fclose(f);
                }
            } else {
                //LOGE("memory low\n");
            }
        }

        err = zip_close(z);
    } else {
        zip_error_to_str(strerr, 1024, err, errno);
        //LOGE("operated zip fail for %s\n", strerr);
    }
}
